import Vue from "vue";
import axios from 'axios';
// import route from "@/routers/router";
const product = 'http://127.0.0.1:9100/product/';
axios.loadData = async (url, method, data = {}) => {
    //默认配置
    let sendObject = {
        data: JSON.stringify(data)
    };
    if (method === 'post') {
        return axios.post(product + url, sendObject.data, {
            headers: {
                'Content-Type': 'application/json;charset=UTF-8'
            },
        });
    } else {
        console.log('get请求');
        return axios.get(product + url);
    }
};
//解决超时问问题重试机制
axios.defaults.retry = 4;
axios.defaults.retryDelay = 1000;
// http request 拦截器
axios.interceptors.request.use(
    config => {
        if (localStorage.token) { //判断token是否存在

            console.log("拦截器token is:");
            console.log(localStorage.token);
            config.headers.Authorization = localStorage.token;  //将token设置成请求头
            console.log('开始config.headers.Authorization...');
            console.log(config.headers.Authorization);
            // config.withCredentials = true; // 允许携带token ,这个是解决跨域产生的相关问题
            config.timeout = 60000
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    }
);

// http response 拦截器
axios.interceptors.response.use(
    response => {
        if (response.data.code === 1) {
            console.log("token过期");
        } else if (response.data.code === 0) {
            console.log(response.data.token);
            window.localStorage['token'] = response.data.token;
        }
        return response;
    },
    error => {
        return Promise.reject(error);
    }
);

// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Vue.prototype.$http = axios;


